<template>
  <van-field
    @click="readonly?'':show = true"
    :label="label"
    v-model="select.text"
    placeholder="请选择"
    is-link
    readonly
    :name="name"
    :rules="rules"
  />
  <van-field
    v-show="false"
    v-model="select.value"
    readonly
    :name="name"
  />
  <van-popup v-model:show="show" closeable :lazy-render="false" teleport="body" :style="{'max-height':'90%'}" position="bottom">
    <t-tree 
      ref="tree"
      @select="confirm" 
      :defaultValue="defaultValue"
      :list="list" 
      :checkbox="checkbox"
      :label-width="labelWidth"
      :value-name="valueName"
      :label-name="labelName"
      :open="open"
    />
  </van-popup>
</template>

<script lang="ts">
import { defineComponent,reactive,toRefs ,watch,nextTick,ref,Ref} from 'vue'
import tTree from "./index.vue"
export default defineComponent({
  name:'tTreeSelect',
  components:{tTree},
  emits:['update:modelValue','select'],
  props:{
    modelValue: String,
    labelWidth:{
      type:String,
      default:'6.2rem'
    },
    rules:{
      type:Array,
      default:[]
    },
    checkbox:{
      type: Boolean,
      default: false
    },
    labelName:{
      type: String,
      default: 'label'
    },
    valueName:{
      type: String,
      default: 'value'
    },
    open:{
      type: Boolean,
      default: false
    },
    readonly:Boolean,
    list:Array,
    name:String,
    label:String
  },
  setup (props,{emit}) {
    const tree = ref()
    const data = reactive({
      show:false,
      defaultValue:props.modelValue||'',
      select:{
        text: '',
        value: props.modelValue||''
      }
    })
    watch(()=>props.modelValue,(nowData:any,prev)=>{
      if(data.show)return;
      data.select.value = nowData;
      data.defaultValue = nowData;
    });
    return {
      ...toRefs(data),
      tree,
      confirm(value,state=true){
        data.select.text = value.map((item)=>item[props.labelName]).join(',');
        data.select.value = value.map((item)=>item[props.valueName]).join(',');
        if(state){
          emit('update:modelValue',data.select.value)
          emit('select',data.select);
        }
        nextTick(()=>{
          data.show = false;
        })
      }
    }
  }
})
</script>